package com.eda;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;

import com.eda.common.ValueConvert;

public class MainActivity extends Activity {
	public static final String LOGGING_INFO = "LOGGING_INFO";
	public static final String USER_NAME ="USER_NAME";
	public static final String PASSWORD ="PASSWORD";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageButton butLogin = (ImageButton) findViewById(R.id.butLogin);
		butLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(R.layout.login_dialog);
			}
		});

		Button ownerPubBut = (Button) findViewById(R.id.mainOwnerPub);
		ownerPubBut.setOnClickListener(mainToOwnerPubListener);

		Button ownerSearchBut = (Button) findViewById(R.id.mainOwnerSearch);
		ownerSearchBut.setOnClickListener(mainToOwnerSearchListener);

		Button pubPubBut = (Button) findViewById(R.id.mainPubPublish);
		pubPubBut.setOnClickListener(mainToPubPublishListener);

		Button pubSearchBut = (Button) findViewById(R.id.mainPubSearch);
		pubSearchBut.setOnClickListener(mainToPubSearchListener);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		return buildLoginDialog(MainActivity.this);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		setTitle("start");
	}

	private Dialog buildLoginDialog(Context context) {
				
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntryView = inflater
				.inflate(R.layout.login_dialog, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setIcon(R.drawable.alert_dialog_icon);
		builder.setTitle(R.string.alert_dialog_text_entry);
		builder.setView(textEntryView);
		
		EditText loginUserName = (EditText)textEntryView.findViewById(R.id.loginUserName);
		EditText loginPassword = (EditText)textEntryView.findViewById(R.id.loginPassword);
		//get new preference
		SharedPreferences loginInfo = getSharedPreferences(LOGGING_INFO,0);
		String name = loginInfo.getString(USER_NAME, "");
		String password = loginInfo.getString(PASSWORD, "");
		loginUserName.setText(name);
		loginPassword.setText(password);
		
		
		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						setTitle("确定");
						
						
						SharedPreferences loginInfo = getSharedPreferences(LOGGING_INFO,0);
						CheckBox saveInfo = (CheckBox)textEntryView.findViewById(R.id.loginSavePwd);
						EditText loginUserName = (EditText)textEntryView.findViewById(R.id.loginUserName);
						EditText loginPassword = (EditText)textEntryView.findViewById(R.id.loginPassword);
						if(saveInfo.isChecked()){
							
							loginInfo.edit()
							.putString(USER_NAME, loginUserName.getText().toString())
							.putString(PASSWORD, loginPassword.getText().toString())
							.commit();
						}
						authorizateUser(loginUserName.getText().toString(),loginPassword.getText().toString());
/*						Intent goUserInfo = new Intent(MainActivity.this,
								UserInfoActivity.class);
						startActivity(goUserInfo);*/
					}
				});
		
		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						setTitle("返回");
					}
				});
		return builder.create();
	}

	private OnClickListener mainToOwnerPubListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent main2OwnerPubIntent = new Intent(MainActivity.this,
					OwnerActivity.class);
			startActivity(main2OwnerPubIntent);

		}
	};

	private OnClickListener mainToOwnerSearchListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent main2OwnerSearchIntent = new Intent(MainActivity.this,
					OwnerActivity.class);
			startActivity(main2OwnerSearchIntent);
		}
	};

	private OnClickListener mainToPubPublishListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent main2PubPublishIntent = new Intent(MainActivity.this,
					PubActivity.class);
			startActivity(main2PubPublishIntent);
		}
	};

	private OnClickListener mainToPubSearchListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent main2PubSearchIntent = new Intent(MainActivity.this,
					PubActivity.class);
			startActivity(main2PubSearchIntent);
		}
	};

	private void authorizateUser(String userName, String password) {
		String url = ValueConvert.URL+"login.do?userName="+userName+"&password="+password;
		HttpClient client = new DefaultHttpClient();
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			
			HttpParams params=client.getParams(); //计算网络超时用. 
			HttpConnectionParams.setConnectionTimeout(params, 3000);
			HttpConnectionParams.setSoTimeout(params, 5000);
			
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					if(out!=null){
						String result = ValueConvert.convert(out).get(0).get(0);
						if(result.equals("success")){
							Intent main2UserInfo = new Intent(MainActivity.this,
									UserInfoActivity.class);
							startActivity(main2UserInfo);
							
						}else if(result.equals("failue")){
							new AlertDialog.Builder(this).setMessage("用户名或密码错误").create().show();
						}else{
							new AlertDialog.Builder(this).setMessage("无法访问服务器").create().show();
						}
					}
					
				}
			}
		} catch (URISyntaxException e) {
			new AlertDialog.Builder(this).setMessage("无法访问服务器").create().show();
		} catch (ClientProtocolException e) {
			new AlertDialog.Builder(this).setMessage("无法访问服务器").create().show();
		} catch (IOException e) {
			new AlertDialog.Builder(this).setMessage("无法访问服务器").create().show();
		}
	}
}
